package com.zhangye.test.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.zhangye.test.entity.HeWeathers;
import com.zhangye.test.entity.Weather;
import com.zhangye.test.model.HeWeather;
import com.zhangye.test.service.HeWeatherService;
import com.zhangye.test.util.HttpTookit;
import com.zhangye.test.util.HttpUtil;
import com.zhangye.test.util.StringUtils;


/**
 * 获取天气
 * 作者： 张叶
 * 创建时间：2018年6月20日  下午4:38:23
 */
@Controller
@RequestMapping("api/weather")
public class HeWeatherApi {
	
	@Autowired
	private HeWeatherService heWeatherService;

	private static final String HOST  = "https://free-api.heweather.com/s6/weather/now";
	
	private static final String GETCID  = "https://free-api.heweather.com/s6/search";

	private static final String APP_KEY  = "99b8e535312d4fba8c94849d1816074d";
 	


	/**
	 * 获取天气
	 * 作者： 张叶
	 * 创建时间：2018年6月20日  下午4:40:31
	 */
	@ResponseBody
	@RequestMapping("/weather")
	public ApiResult weather(String lat,String lng) {
		ApiResult result = new ApiResult();
		HeWeather hw = new HeWeather();
		String cid = getCid(lat, lng);
		if(cid != null && !"".equals(cid)){
			String where = " and cid = '" + cid + "'";
			List<HeWeather> list = heWeatherService.selectByWhere(where);
			if(list.size() > 0){//数据库数据，
				Date createDate = list.get(0).getCreateDate();
				int day = StringUtils.diffMs(createDate,new Date(),"d");
				int hour = StringUtils.diffMs(createDate,new Date(),"h");
				if(day >=1 || hour >= 1){//更新
			        hw = getNowWeather(cid,list.get(0).getId());
				}else{//直接返回
					hw = list.get(0);
				}
			}else{//数据库暂无数据，添加
		        hw = getNowWeather(cid,null);
			}
		}
		result.data.put("hw", hw);
		return result;
	}


	/**
	 * 获取城市ID
	 * 作者： 张叶
	 * 创建时间：2018年6月21日  下午5:39:01
	 */
	private String getCid(String lat,String lng) {
		String cid = "";
        Map<String, String> map = new HashMap<String, String>();
		map.put("location", lat + "," + lng);
        map.put("key", APP_KEY);
        String a = HttpTookit.doGet(GETCID,map);
		Gson gson = new Gson();
		HeWeathers w = gson.fromJson(a,HeWeathers.class);
		if(w.getHeWeather6().size() > 0){
			cid = w.getHeWeather6().get(0).getBasic().getCid();
		}
		return cid;
	}


	/**
	 * 获取当前天气
	 * 作者： 张叶
	 * 创建时间：2018年6月21日  下午5:38:46
	 */
	private HeWeather getNowWeather(String cid,Long id) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("location", cid);
		map.put("key", APP_KEY);
		String a = HttpTookit.doGet(HOST,map); 
		Gson gson = new Gson();
		HeWeathers w = gson.fromJson(a,HeWeathers.class);
		Weather weather = w.getHeWeather6().get(0);
		HeWeather hw = insertWeather(weather,id);
		return hw;
	}
	
	
	public ApiResult getCity(String lat,String lng) {
		ApiResult result = new ApiResult();
		String key = "ff53d41333699e71213e01ed52a73761";
		String location = String.format("%s,%s", lng, lat);
        String url = String.format("http://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s&poitype=&radius=&extensions=all&batch=false&roadlevel=", key, location);
        String content = HttpUtil.requestGet(url);
        JSONObject json = JSONObject.parseObject(content);
        if ("1".equalsIgnoreCase(json.getString("status"))) {//正常
            JSONObject a = json.getJSONObject("regeocode").getJSONObject("addressComponent");
            String district = a.getString("district");
            String adcode = a.getString("adcode");
            String township = a.getString("township");
            String address = json.getJSONObject("regeocode").getString("formatted_address");
            String city = a.getString("city");
    		result.data.put("district", district);
    		result.data.put("adcode", adcode);
    		result.data.put("township", township);
    		result.data.put("address", address);
    		result.data.put("city", city);
        }
		return result;
	}


	
	private HeWeather insertWeather(Weather weather,Long id) {
		if(id != null){
			heWeatherService.delete(id);
		}
		HeWeather hw = new HeWeather();
		hw.setCid(weather.getBasic().getCid());
		hw.setLocation(weather.getBasic().getLocation());
		hw.setAdminArea(weather.getBasic().getAdmin_area());
		hw.setCnty(weather.getBasic().getCnty());
		hw.setCondTxt(weather.getNow().getCond_txt());
		hw.setWindDir(weather.getNow().getWind_dir());
		hw.setUpdateDate(weather.getUpdate().getLoc());
		hw.setFl(weather.getNow().getFl());
		hw.setTmp(weather.getNow().getTmp());
		hw.setCreateDate(new Date());
		heWeatherService.insert(hw);
		return hw;
	}
}
